package com.test.study.jdbc;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;

import javax.sql.DataSource;

/**
 * 数据库连接池
 * @author huyong
 *
 */
public class MyDataSourcePool implements DataSource {
	private static final Logger LOGGER = Logger.getLogger(MyDataSourcePool.class.getCanonicalName());
	private static CopyOnWriteArrayList<Connection> dataSourcePool = new CopyOnWriteArrayList<Connection>();

	/**
	 * 初始化连接池
	 * @param count
	 */
	public MyDataSourcePool(int count) {
		for (int i = 0; i < count; i++) {
			Connection connection = JdbcUtils.getConnection();
			dataSourcePool.add(connection);
		}
		LOGGER.info("init datasource pool size  ===> "+dataSourcePool.size());
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {

	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	/**
	 * 获取连接
	 */
	@Override
	public Connection getConnection() throws SQLException {
		if (dataSourcePool.size() == 0) {
			LOGGER.warning("datasource pool is empty");
			return null;
		}
		Connection connection = dataSourcePool.remove(0);
		//将增强以后的连接返回
		MyConnectionWrapper connectionWrapper = new MyConnectionWrapper(connection, dataSourcePool);
		LOGGER.warning("datasource pool size ==> "+dataSourcePool.size());
		return connectionWrapper;
	}
	
	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return null;
	}

}
